/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javacommunity.model.dao.impl;

import com.javacommunity.model.dao.PostDAO;
import com.javacommunity.model.entity.Post;
import com.javacommunity.hibernate.HibernateUtil;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Pham
 */
public class PostDAOImpl implements PostDAO {

    private static PostDAOImpl postDAO;

    public static PostDAOImpl getInstance() {
        if (postDAO == null) {
            postDAO = new PostDAOImpl();
        }
        return postDAO;
    }

    private Session session;
    private Transaction ts;

    @Override
    public Post getPostById(int postId) {
        session = HibernateUtil.getSessionFactory().openSession();
        Post post = null;
        try {
            ts = session.beginTransaction();
            post = (Post) session.get(Post.class, postId);

            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return post;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Post> getPosts(int param) {
        session = HibernateUtil.getSessionFactory().openSession();
        List<Post> posts = null;
        try {
            ts = session.beginTransaction();
            Query query = session.createSQLQuery("CALL sp_GetPosts(?)").addEntity(Post.class).setParameter(0, param);
            posts = query.list();
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return posts;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Post> getListOfPost(int firstRow, int rowCount) {
        session = HibernateUtil.getSessionFactory().openSession();
        List<Post> posts = null;
        try {
            ts = session.beginTransaction();
            Query query = session.createQuery("From Post where active = true");
            query.setFirstResult(firstRow);
            query.setMaxResults(rowCount);
            posts = (List<Post>) query.list();
            ts.commit();
        } catch (Exception e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return posts;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Post> getPostMostViewed() {
        session = HibernateUtil.getSessionFactory().openSession();
        List<Post> posts = null;
        try {
            ts = session.beginTransaction();
            posts = session.createQuery("From Post order by viewCount desc").list();
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return posts;
    }

    @Override
    public boolean createPost(Post post) {
        boolean isCheck = false;
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            session.save(post);
            ts.commit();
            isCheck = true;
        } catch (Exception e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return isCheck;
    }

    @Override
    public boolean updatePost(Post post) {
        boolean isCheck = false;
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            String sql = "UPDATE Post p set p.title = ?, p.content = ?, p.attachPath = ?"
                    + ", p.updateDate = ?, p.category = ? WHERE p.postId = ?";
            Query query = session.createQuery(sql);
            query.setParameter(0, post.getTitle());
            query.setParameter(1, post.getContent());
            query.setParameter(2, post.getAttachPath());
            query.setParameter(3, post.getUpdateDate());
            query.setParameter(4, post.getCategory());
            query.setParameter(5, post.getPostId());
            query.executeUpdate();
            ts.commit();
            isCheck = true;
        } catch (Exception e) {
            e.printStackTrace();
            if (ts != null) {
                ts.rollback();
            }
            
        } finally {
            session.close();
        }
        return isCheck;
    }

    @Override
    public boolean updateViewCount(Post post) {
        boolean isCheck = false;
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            String sql = "UPDATE Post as p set p.viewCount = ? WHERE p.postId = ?";
            Query query = session.createQuery(sql);
            query.setParameter(0, post.getViewCount());
            query.setParameter(1, post.getPostId());
            query.executeUpdate();
            ts.commit();
            isCheck = true;
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return isCheck;
    }

    @Override
    public boolean deletePost(Post post) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            session.createQuery("Delete FROM Comment c Where c.post = ?").setParameter(0, post).executeUpdate();
            session.createQuery("Delete FROM UserPost up Where up.post = ?").setParameter(0, post).executeUpdate();
            session.delete(post);
            ts.commit();
            return true;
        } catch (Exception e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public boolean removePost(Post post) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            String sql = "UPDATE Post set active = false WHERE postId = ?";
            Query query = session.createQuery(sql);
            query.setParameter(0, post.getPostId());
            query.executeUpdate();
            ts.commit();
            return true;
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public boolean restorePost(Post post) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            ts = session.beginTransaction();
            String sql = "UPDATE Post set active = true WHERE postId = ?";
            Query query = session.createQuery(sql);
            query.setParameter(0, post.getPostId());
            query.executeUpdate();
            ts.commit();
            return true;
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

}
